﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Text;
using System.IO;
using System.IO.IsolatedStorage;

namespace BuyTrainTicket
{
    public partial class TrainList : PhoneApplicationPage
    {
        private string username;
        private string password;
        private string key;
        List<Item> items = new List<Item>();
        public TrainList()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            string msgJson = "";
            if (NavigationContext.QueryString.TryGetValue("msgJson", out msgJson))
            {
                JObject respJObject = JsonConvert.DeserializeObject<JObject>(msgJson);
                JToken isSuccess = respJObject.GetValue("isSuccess");
                if ((bool)isSuccess == true)
                {
                    key = (string)respJObject.GetValue("key");
                    IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
                    settings.TryGetValue<String>("username", out username);
                    settings.TryGetValue<String>("password", out password);
                    if (username == null || password == null)
                    {
                        MessageBox.Show("请先设置用户名和密码");
                        NavigationService.Navigate(new Uri("/Setting.xaml", UriKind.Relative));
                        return;
                    }
                    sendRequest(Util.host + "/servlet/Buy12306Servlet?action=getresponse&password=" + password + "&username=" + username + "&type==getresponse&version=8.1");


                }
            }
        }

        void sendRequest(string url)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.BeginGetRequestStream(new AsyncCallback(getRequestCallback), request);
            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("网络错误，请稍后再试1");

                });
            }
        }

        void getRequestCallback(IAsyncResult asyncResult)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;

                Stream postStream = request.EndGetRequestStream(asyncResult);

                StringBuilder postData = new StringBuilder();
                postData.Append("key=" + key);

                byte[] byteArray = Encoding.UTF8.GetBytes(postData.ToString());

                postStream.Write(byteArray, 0, byteArray.Length);
                postStream.Close();

                request.BeginGetResponse(new AsyncCallback(getResponseCallback), request);
            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("网络错误，请稍后再试2");

                });
            }
        }

        void getResponseCallback(IAsyncResult asyncResult)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);

                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    byte[] byteArray = new byte[response.ContentLength];
                    response.GetResponseStream().Read(byteArray, 0, (int)response.ContentLength);
                    String responseStr = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
                    JObject responseObj = JsonConvert.DeserializeObject<JObject>(responseStr);
                    if ((bool)responseObj.GetValue("isSuccess") == true)
                    {
                        JToken respHtml = responseObj.GetValue("respHtml");
                        string[] trainInfos = ((String)respHtml).Split('|');
                        foreach (string trainInfo in trainInfos)
                        {
                            StringBuilder sb = new StringBuilder();
                            String[] postInfos = trainInfo.Split(';')[1].Split('#');
                            String station_train_code = postInfos[0];
                            String lishistr = postInfos[1];
                            String starttimestr = postInfos[2];
                            String trainno4 = postInfos[3];
                            String from_station_telecode = postInfos[4];
                            String to_station_telecode = postInfos[5];
                            String arrive_time = postInfos[6];
                            String from_station_name = postInfos[7];
                            String to_station_name = postInfos[8];
                            String[] ticketsInfo = trainInfo.Split(';')[0].Split(',');
                            sb.Append("车次：").Append(station_train_code).Append("\t\t").Append("发站：")
                                .Append(from_station_name).Append("\t\t").Append("到站：").Append(to_station_name)
                                .Append("\n").Append("历时：").Append(lishistr).Append("\t\t").Append("发时：")
                                .Append(starttimestr).Append("\t\t").Append("到时：").Append(arrive_time).Append("\n")
                                .Append("商务座：").Append(ticketsInfo[0]).Append("\t\t").Append("特等座：").Append(ticketsInfo[1]).Append("\n")
                                .Append("一等座：").Append(ticketsInfo[2]).Append("\t\t").Append("二等座：").Append(ticketsInfo[3]).Append("\n")
                                .Append("高级软卧").Append(ticketsInfo[4]).Append("\t\t").Append("软卧：").Append(ticketsInfo[5]).Append("\t\t").Append("硬卧：").Append(ticketsInfo[6]).Append("\n")
                                .Append("软座：").Append(ticketsInfo[7]).Append("\t\t").Append("硬座：").Append(ticketsInfo[8]).Append("\t\t").Append("无座：").Append(ticketsInfo[9]).Append("\n");
                            items.Add(new Item(sb.ToString()));
                        }
                        Dispatcher.BeginInvoke(() =>
                        {
                            trainList.ItemsSource = items;
                        });
                    }
                    else
                    {
                        string errMsg = (string)responseObj.GetValue("errMsg");
                        Dispatcher.BeginInvoke(() =>
                        {
                            MessageBox.Show(errMsg);
                        });
                    }
                }
                else
                {
                    Dispatcher.BeginInvoke(() =>
                           {
                               MessageBox.Show(response.StatusCode.ToString());
                           });
                }
            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("网络错误，请稍后再试3");

                });
            }
        }
    }

    public class Item
    {
        public string ItemContent { get; private set; }

        public Item(string _ItemContent)
        {
            ItemContent = _ItemContent;
        }
    }
}